import React, { useState, useEffect } from "react";
import {
  BrowserRouter as Router,
  Routes,
  Route,
  useNavigate,
  useParams,
} from "react-router-dom";
import VideoList from "./pages/VideoList";
import VideoDetail from "./pages/VideoDetail";
import MobileLogin from "./pages/MobileLogin";
import Footer from "./components/Footer";
import type { VidVideo_ } from "./api/models/VidVideo_";
import { VidUser_ } from "./api/models/VidUser_";
import { useUser, useInitializeUser } from "./stores/userStore";

import "./App.css";

// 视频详情页面组件
const VideoDetailPage: React.FC = () => {
  const { videoId } = useParams<{ videoId: string }>();
  const navigate = useNavigate();
  const [video, setVideo] = useState<VidVideo_ | null>(null);

  useEffect(() => {
    // 从localStorage获取视频信息（实际项目中应该通过API获取）
    const savedVideo = localStorage.getItem(`video_${videoId}`);
    if (savedVideo) {
      try {
        setVideo(JSON.parse(savedVideo));
      } catch (error) {
        console.error("解析视频信息失败:", error);
        navigate("/h5");
      }
    } else {
      // 如果没有视频信息，返回首页
      navigate("/h5");
    }
  }, [videoId, navigate]);

  const handleBack = () => {
    navigate("/h5");
  };

  const handleLoginRequired = () => {
    navigate("/login");
  };

  const handleVideoClick = (video: VidVideo_) => {
    // 保存视频信息到localStorage并导航到新的视频详情页
    localStorage.setItem(`video_${video.id}`, JSON.stringify(video));
    navigate(`/h5/video/${video.id}`);
  };

  if (!video) {
    return <div>加载中...</div>;
  }

  return (
    <VideoDetail
      video={video}
      onBack={handleBack}
      onLoginRequired={handleLoginRequired}
      onVideoClick={handleVideoClick}
    />
  );
};

// 视频列表页面组件
const VideoListPage: React.FC = () => {
  const navigate = useNavigate();
  const { userInfo, setUserInfo } = useUser();

  const handleVideoClick = (video: VidVideo_) => {
    // 保存视频信息到localStorage（实际项目中可以通过URL参数传递）
    localStorage.setItem(`video_${video.id}`, JSON.stringify(video));
    navigate(`/h5/video/${video.id}`);
  };

  const handleLoginRequired = () => {
    navigate("/h5/login");
  };

  const handleLogout = () => {
    // 使用store的logout方法
    setUserInfo(null);
    // 刷新页面
    window.location.reload();
  };

  return (
    <VideoList
      onVideoClick={handleVideoClick}
      onLoginClick={handleLoginRequired}
      onLogout={handleLogout}
    />
  );
};

// 登录页面组件
const LoginPage: React.FC = () => {
  const navigate = useNavigate();
  const { setUserInfo } = useUser();

  const handleLoginSuccess = (user: VidUser_) => {
    setUserInfo(user);
    // 登录成功后返回上一页或首页
    const from =
      new URLSearchParams(window.location.search).get("from") || "/h5";
    navigate(from);
  };

  const handleClose = () => {
    navigate(-1); // 返回上一页
  };

  return (
    <MobileLogin
      onLoginSuccess={handleLoginSuccess}
      onClose={handleClose}
      isModal={false}
    />
  );
};

// 用户状态初始化组件
const UserInitializer: React.FC<{ children: React.ReactNode }> = ({
  children,
}) => {
  const initializeUser = useInitializeUser();

  useEffect(() => {
    initializeUser();
  }, [initializeUser]);

  return <>{children}</>;
};

// 主应用组件
const App: React.FC = () => {
  return (
    <Router>
      <UserInitializer>
        <div className="app">
          <Routes>
            <Route path="/h5" element={<VideoListPage />} />
            <Route path="/h5/video/:videoId" element={<VideoDetailPage />} />
            <Route path="/h5/login" element={<LoginPage />} />
          </Routes>
          <Footer />
        </div>
      </UserInitializer>
    </Router>
  );
};

export default App;
